package com.guodexian.controller;
import com.guodexian.dto.UserDto;
import com.guodexian.entity.User;
import com.guodexian.service.SmsService;
import com.guodexian.service.UserService;
import com.guodexian.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 类说明：<br>
 *
 * @author qfrx<br>
 * 2024/12/25 10:57<br>
 * @since 1.0 <br>
 */
@Controller
@CrossOrigin
@RequestMapping("/visitor")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    @ResponseBody
    public R<User> login(String userTel, String userPass) {
        User user=userService.findUserByTelAndPass(userTel, userPass);
        return  R.OK.setData(user);
    }
    @Autowired
    private SmsService smsService;

    @RequestMapping("/send/{userTel}")
    @ResponseBody
    public R<String>  sendMsg(@PathVariable("userTel") String userTel, HttpServletRequest request) throws Exception {
        //六位随机数
        int code = new Random().nextInt(900000) + 100000;
        String ret = smsService.sendSms(userTel, code + "");
        System.out.println("=========="+code);
        //后面还需要在注册时候比对用户输入的验证码是否和这个，以手机号为主键。前后端分离不存在会话之
        Map<String, String> codeMap = (Map<String, String>) request.getServletContext().getAttribute("codeMap");
        if (codeMap == null) {
            codeMap = new HashMap<>();
            request.getServletContext().setAttribute("codeMap", codeMap);
        }
        codeMap.put(userTel, code + "");
        return R.OK.setData(ret);
    }
    @RequestMapping("/reg")
    public R<String> register(@RequestBody UserDto userDto, HttpServletRequest request) throws Exception {
        System.out.println(userDto );
        System.out.println("========================================");
        //先验证验证码
        Map<String, String> codeMap = (Map<String, String>) request.getServletContext().getAttribute("codeMap");
        if (codeMap == null) {
            codeMap = new HashMap<>();
            request.getServletContext().setAttribute("codeMap",codeMap);
        }

        String code = codeMap.get(userDto.getUserTel());
        if(code == null){
            return R.FAIL.setMsg("没有找到验证码");
        }
        if(! code.equals(userDto.getCode())){
            return R.FAIL.setMsg("验证码错误！");
        }
        userService.reg(userDto);
        return R.OK;
    }
}
